/**
 * axios实例
 */
import axios from 'axios';
import type { AxiosResponse } from 'axios';
import type { Action } from 'element-plus';
import { ElMessageBox } from 'element-plus/es';
/**
 * 接口统一返回结果
 */
export interface ApiResult<T> {
  /** 状态码 */
  code: number;
  /** 状态信息 */
  msg?: string;
  /** 返回数据 */
  data?: T;
}

const apiPrefix: string = process.env.XS_API_URL ? process.env.XS_API_URL : '/webapi'
const apiUrl = process.env.XS_LOCAL_URL ? '/' : process.env.XS_OPEN_PROXY_PATH
/** 创建axios实例 */
const service = axios.create({
  baseURL: apiUrl + apiPrefix
});

/**
 * 添加请求拦截器
 */
service.interceptors.request.use(
  (config) => {
    config.headers['clientId'] = 'website';
    // 添加token到header
    if (config.data.TOKEN === 1) {
      const token = userStore().getToken();
      config.headers['Authorization'] = token;
    }
    delete config.data.TOKEN
    if (config.method === 'post') {
      config.data['transDate'] = String(Date.now());
      config.data['transNonce'] = getuuid();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 添加响应拦截器
 */
service.interceptors.response.use(
  (res: AxiosResponse) => {
    console.log(res)
    if (res.data?.code != 0) {
      ElMessage({
        message: res.data.msg || '请求错误~',
        type: "error",
      });
      return Promise.reject(res.data.msg || '请求错误~');
    }
    return res.data;
  },
  (error) => {
    console.log(error);
    // 登录过期处理
    if (error.response.status === 401 || error.response.status === 424) {
      ElMessageBox.close();
      userStore().removeToken()
      ElMessageBox.alert('登录状态已过期, 请退出重新登录!', '系统提示', {
        confirmButtonText: '重新登录',
        showClose: false,
        callback: (action: Action) => {
          if (action === 'confirm') {
            location.href = '/'
          }
        },
        type: 'warning',
        draggable: true
      });
      return Promise.reject(error.response.data.msg || '请求错误~');
    }
    return Promise.reject(error);
  }
);

export function post(url: string, data: Object, token: Boolean = false) {
  return service.post(url, { ...data, TOKEN: Number(token) })
}

